import lodash from 'lodash';
import KeyGenerator from 'uuid-key-generator';
import Calc from '../lib/calc';
import Modifiers from './modifiers';

//购物车一种商品
export default class Inventoryitem {
  constructor(inventory) {
    // debugger
    var keygen = new KeyGenerator(KeyGenerator.BASE36);
    inventory = inventory || {}
    this.id = keygen.generateKey();
    this.price = 0;
    this.inventoryId = inventory.id || "";
    this.inventoryName = inventory.name || "";
    this.categories = inventory.categories || "";
    this.inventoryCode = inventory.code || "";
    this.costPrice = inventory.costPrice;
    this.qty = 0;
    this.extended = {};
    this.extended.description = "";
    this.extended.categories = inventory.categories || [];
    this.modifiers = new Modifiers(inventory.modifiers instanceof Array ?
      inventory.modifiers : (inventory.modifiers && inventory.modifiers.items)
    );
    this.inventory = this.inventory || {};
    this.inventory.unit = inventory.unit;
    this.oldModifiers = inventory.modifiers;
  }

  // get&&get
  get amount() {
    let p = (this.modifiers && this.modifiers.amount) || 0;
    // return (p + this.price) * this.qty;
    return Calc.reserveFixed2(Calc.accAdd(p, this.price) * this.qty);
  }

  setNewInventoryitem(inventoryitem) {
    const self = this;
    for (var variable in inventoryitem) {
      if (inventoryitem.hasOwnProperty(variable)) {
        if (variable == "modifiers") {
          // debugger
          inventoryitem[variable].items.forEach(v => {
            self[variable].pushModifiersItem(v);
          })
        } else if (variable != "amount") {
          this[variable] = inventoryitem[variable];
        }
      }
    }
  }

  setDescription(description) {
    this.extended.description = description;
  }

  toJSON() {
    return lodash.extend({}, lodash.clone(this), {
      amount: this.amount
    });
  }
}
